import Taro from "@tarojs/taro";
import { set as setGlobalData, get as getGlobalData } from '../utils/global_data';

export const API_PATH = "https://wzj-ipark.com/project";
export const token = () => {
    return getGlobalData('token');
}
const AUTHOR = () => {
    const cacheEffectiveTime = Taro.getStorageSync('cacheEffectiveTime');
    const now = new Date().getTime();
    const cacheTime = new Date(cacheEffectiveTime.replace(/-/g, "/")).getTime();
    // cacheEffectiveTime 为null 说明没有登录过
    if (now > cacheTime && cacheEffectiveTime) {
        // token过期
        Taro.login({
            success: function (res) {
                if (res.code) {
                    Api.wxLogin({
                        code: res.code
                    }).then(res => {
                        setGlobalData("token", res.token);
                        Taro.setStorage({
                            key: "cacheToken",
                            data: res.token
                        });
                        Taro.setStorage({
                            key: "cacheEffectiveTime",
                            data: res.effectiveTime
                        });
                        return `Bearer ${res.token}`;
                    });
                } else {
                    console.log('登录失败！' + res.errMsg);
                }
            }
        })
    }
    return `Bearer ${getGlobalData('token')}`;
}

const Router = {
    // 查询字典
    GET_LISTIT: `${API_PATH}/app/project/show/listIt`,
    GET_STAGE: `${API_PATH}/app/project/show/listStage`,

    // 成果
    GET_ACH_LIST: `${API_PATH}/app/project/show/listProject`,
    GET_ACH_DETAIL: `${API_PATH}/app/project/show/detailProject`,

    // 评论
    GET_COMMENT_SELF: `${API_PATH}/app/project/show/listCommentSelf`,
    GET_COMMENT_OTHER: `${API_PATH}/app/project/show/listCommentOther`,
    ADD_COMMENT: `${API_PATH}/app/project/operate/addComment`,
    DEL_COMMENT: `${API_PATH}/app/project/operate/delComment`,

    // 操作
    ADD_COLLECT: `${API_PATH}/app/project/operate/addCollect`,
    DEL_COLLECT: `${API_PATH}/app/project/operate/delCollect`,
    ADD_LIKE: `${API_PATH}/app/project/operate/addPraise`,
    DEL_LIKE: `${API_PATH}/app/project/operate/delPraise`,

    // 我的
    GET_MY_COLLECT: `${API_PATH}/app/project/show/listSelfCollect`,
    GET_MY_LIKE: `${API_PATH}/app/project/show/listSelfPraise`,
    GET_MY_COMMENT: `${API_PATH}/app/project/show/listSelfComment`,

    // 用户
    WX_LOGIN: `${API_PATH}/wxLogin`,
    USER_EDIT: `${API_PATH}/app/user/edit`,
    USER_AVATAR: `${API_PATH}/system/user/profile/avatar`,
    GET_USER: `${API_PATH}/app/user/detail`,
}

export class Api {

    // 查询方向字典
    static async getListIt() {
        const url = Router.GET_LISTIT;
        const header = {
            'Authorization': AUTHOR()
        };
        return Get(url, {}, header);
    }

    // 查询阶段字典
    static async getStage() {
        const url = Router.GET_STAGE;
        const header = {
            'Authorization': AUTHOR()
        };
        return Get(url, {}, header);
    }

    // 分页查询成果列表
    static async getAchList({pageSize, pageNum, proName, itIds, stages}) {
        const url = Router.GET_ACH_LIST + `?pageSize=${pageSize}&pageNum=${pageNum}&proName=${proName}&itIds=${itIds}&stages=${stages}`;
        const header = {
            'Authorization': AUTHOR()
        };
        return Get(url, {}, header);
    }

    // 查询成果详情
    static async getAchDetail({proId}) {
        const url = Router.GET_ACH_DETAIL + `?proId=${proId}`;
        const header = {
            'Authorization': AUTHOR()
        };
        return Get(url, {}, header);
    }

    // 查询自己的评论列表
    static async getCommentSelf({proId}) {
        const url = Router.GET_COMMENT_SELF + `?proId=${proId}`;
        const header = {
            'Authorization': AUTHOR()
        };
        return Get(url, {}, header);
    }

    // 分页查询别人的评论列表
    static async getCommentOther({proId, pageSize, pageNum}) {
        const url = Router.GET_COMMENT_OTHER + `?proId=${proId}&pageSize=${pageSize}&pageNum=${pageNum}`;
        const header = {
            'Authorization': AUTHOR()
        };
        return Get(url, {}, header);
    }

    // 添加评论
    static async addComment({proId, content}) {
        const url = Router.ADD_COMMENT;
        const header = {
            'Authorization': AUTHOR(),
            'Content-Type': 'application/json'
        };
        const data = {
            proId, content
        };
        return Post(url, data, header);
    }

    // 删除评论
    static async delComment(id) {
        const url = Router.DEL_COMMENT + `/${id}`;
        const header = {
            'Authorization': AUTHOR(),
        };
        return Post(url, {}, header);
    }

    // 新增收藏
    static async addCollect({proId}) {
        const url = Router.ADD_COLLECT;
        const header = {
            'Authorization': AUTHOR(),
            'Content-Type': 'application/json'
        };
        const data = {
            proId
        };
        return Post(url, data, header);
    }

    // 删除收藏
    static async delCollect({proId}) {
        const url = Router.DEL_COLLECT + `/${proId}`;
        const header = {
            'Authorization': AUTHOR()
        };
        return Post(url, {}, header);
    }

    // 新增点赞
    static async addLike({proId}) {
        const url = Router.ADD_LIKE;
        const header = {
            'Authorization': AUTHOR(),
            'Content-Type': 'application/json'
        };
        const data = {
            proId
        };
        return Post(url, data, header);
    }

    // 删除点赞
    static async delLike({proId}) {
        const url = Router.DEL_LIKE + `/${proId}`;
        const header = {
            'Authorization': AUTHOR()
        };
        return Post(url, {}, header);
    }

    // 查询自己的收藏列表
    static async getMyCollect({pageSize, pageNum}) {
        const url = Router.GET_MY_COLLECT + `?pageSize=${pageSize}&pageNum=${pageNum}`;
        const header = {
            'Authorization': AUTHOR()
        };
        return Get(url, {}, header);
    }

    // 查询自己的点赞列表
    static async getMyLike({pageSize, pageNum}) {
        const url = Router.GET_MY_LIKE + `?pageSize=${pageSize}&pageNum=${pageNum}`;
        const header = {
            'Authorization': AUTHOR()
        };
        return Get(url, {}, header);
    }

    // 登录、注册
    static async wxLogin({code}) {
        const url = Router.WX_LOGIN + `?code=${code}`;
        return Post(url, {}, {});
    }

    // 查询自己的评论项目列表
    static async getMyComment({pageSize, pageNum}) {
        const url = Router.GET_MY_COMMENT + `?pageSize=${pageSize}&pageNum=${pageNum}`;
        const header = {
            'Authorization': AUTHOR()
        };
        return Get(url, {}, header);
    }

    // 上传头像
    static async uploadAvatar({avatarfile}) {
        const url = Router.USER_AVATAR;
        const header = {
            'Authorization': AUTHOR(),
            'Content-Type': 'multipart/form-data'
        };
        return uploadFileForm({
            url,
            filePath: avatarfile,
            name: 'avatarfile',
            header
        });
    }

    // 修改用户信息
    static async editUser(data) {
        const url = Router.USER_EDIT;
        const header = {
            'Authorization': AUTHOR(),
            'Content-Type': 'application/json'
        };
        return Post(url, data, header);
    }

    // 获取用户信息
    static async getUserDetail() {
        const url = Router.GET_USER;
        const header = {
            'Authorization': AUTHOR()
        };
        return Get(url, {}, header);
    }
}

// 成功code: 200
async function request({url, data, header = {}, method}) {
    // try {
    //     const cacheToken = Taro.getStorageSync('token');
    //
    //     if (cacheToken) {
    //         header = {
    //             thirdSessionKey: cacheToken,
    //             ...header
    //         }
    //     }
    // } catch (error) {
    //     console.log('获取cacheToken异常: ', error);
    // }
    try {
        const {data: resData} = await new Promise((resolve, reject) => {
            Taro.request({
                url: url,
                data,
                header,
                method,
                success(res) {
                    resolve(res)
                },
                fail(res) {
                    reject(res)
                }
            })
        })

       const {code} = resData;
        if (code === 200) {
            if (resData.hasOwnProperty('data')) {
                return resData.data;
            } else {
                return resData;
            }
        }
        throw new Error(resData.msg);
    } catch (error) {
        console.log('error: ', error);
        throw error;
    }
}

async function uploadFileForm({url, filePath, name, formData, header}) {
    try {
        const {data: resData} = await new Promise((resolve, reject) => {
            Taro.uploadFile({
                url,
                filePath,
                name,
                formData,
                header,
                success(res) {
                    resolve(res)
                },
                fail(res) {
                    reject(res)
                }
            })
        })

        let resDataParse = JSON.parse(resData);
        const {code} = resDataParse;
        if (code === 200) {
            if (resDataParse.data) {
                return resDataParse.data;
            } else {
                return resDataParse;
            }
        }
        throw new Error(resDataParse.msg);
    } catch (error) {
        console.log('error: ', error);
        throw error;
    }
}

function Post(url, data, header) {
    return request({url, data, header, method: 'POST'})
}

function Get(url, data, header) {
    return request({url, data, header, method: 'GET'})
}
